<script setup lang="ts">
import type { GiSvgIconProps } from '#/components/gi-svg-icon/type';

import { computed } from 'vue';

defineOptions({ name: 'GiSvgIcon' });

const props = withDefaults(defineProps<GiSvgIconProps>(), {
  name: '',
  color: '',
  size: 20,
});

// 判断传入的值，是否带有单位，如果没有，就默认用px单位
const getUnitValue = (value: number | string): number | string => {
  return /(?:px|em|rem|%)$/.test(value.toString()) ? value : `${value}px`;
};

const iconSize = computed<number | string>(() => {
  return getUnitValue(props.size);
});

const iconName = computed(() => {
  // 如果名称已经包含 icon- 前缀，则直接使用
  if (props.name.startsWith('icon-')) {
    return `#${props.name}`;
  }
  // 否则添加 icon- 前缀
  return `#icon-${props.name}`;
});

const svgClass = computed(() => {
  if (props.name) return `svg-icon icon-${props.name}`;
  return 'svg-icon';
});

const iconStyle = computed(() => {
  const style: Record<string, string> = {
    width: iconSize.value as string,
    height: iconSize.value as string,
  };

  if (props.color) {
    style.color = props.color;
    style.fill = props.color;
    style.stroke = props.color;
  }

  return style;
});
</script>

<template>
  <svg aria-hidden="true" :class="svgClass" v-bind="$attrs" :style="iconStyle">
    <use :xlink:href="iconName" />
  </svg>
</template>

<style scoped lang="scss">
.svg-icon {
  flex-shrink: 0;
  width: auto;
  height: auto;
  vertical-align: middle;
  fill: currentcolor;
  stroke: currentcolor;
}
</style>
